package com.zretc.security.filter;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zretc.api.pojo.SysUser;
import com.zretc.api.pojo.User;
import com.zretc.common.constant.SecurityConstant;
import com.zretc.common.entity.R;
import com.zretc.common.util.WebUtil;
import com.zretc.redis.service.RedisService;
import com.zretc.security.entity.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private RedisService redisService;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        response.setContentType("html/text;charset=utf-8");

        //查询是否从gateway中获得白名单特殊字段
        String whiteHeader = request.getHeader(SecurityConstant.WHITE_HEADER_NAME);
        if(StringUtils.hasText(whiteHeader)){
            //创建匿名权限 并设置
            setWhiteAuthentication();
            filterChain.doFilter(request,response);
            return;
        }


        String key = request.getHeader(SecurityConstant.AUTHENTICATION_KEY);
        if(StringUtils.isEmpty(key)){
            WebUtil.sendResp(response,JSON.toJSONString(R.fail(402,"key不能为空")));
            return;
        }

        //从redis获取用户信息
        String redisKey = "login:" + key;
        LoginUser loginUser = redisService.getCacheObject(redisKey);
        if(Objects.isNull(loginUser)){

            WebUtil.sendResp(response, new ObjectMapper().writeValueAsString(R.genRespObj(401, "登录超时", null)));
            return;
        }
        //修改验证成功状态
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
        //将用户信息存放到SecurityContextHolder
        //阻止后续过滤器链调用
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //放行请求
        filterChain.doFilter(request,response);
    }
    //设置匿名用户到SecurityContextHolder中 从而阻止过滤器链的调用
    public void setWhiteAuthentication(){
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(new LoginUser(new User(),null,null),null,null);
        //将用户信息存放到SecurityContextHolder
        //阻止后续过滤器链调用
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
    }
}
